﻿var core = {

    debounce: function (func, wait, immediate) {
        // immediate默认为false
        var timeout, args, context, timestamp, result;

        var later = function () {
            // 当wait指定的时间间隔期间多次调用_.debounce返回的函数，则会不断更新timestamp的值，导致last < wait && last >= 0一直为true，从而不断启动新的计时器延时执行func
            var last = _.now() - timestamp;

            if (last < wait && last >= 0) {
                timeout = setTimeout(later, wait - last);
            } else {
                timeout = null;
                if (!immediate) {
                    result = func.apply(context, args);
                    if (!timeout) context = args = null;
                }
            }
        };

        return function () {
            context = this;
            args = arguments;
            timestamp = _.now();
            // 第一次调用该方法时，且immediate为true，则调用func函数
            var callNow = immediate && !timeout;
            // 在wait指定的时间间隔内首次调用该方法，则启动计时器定时调用func函数
            if (!timeout) timeout = setTimeout(later, wait);
            if (callNow) {
                result = func.apply(context, args);
                context = args = null;
            }

            return result;
        };
    },
    guid: function () {

        var s = [];
        var hexDigits = "0123456789abcdef";
        for (var i = 0; i < 36; i++) {
            s[i] = hexDigits.substr(Math.floor(Math.random() * 0x10), 1);
        }
        s[14] = "4";  // bits 12-15 of the time_hi_and_version field to 0010
        s[19] = hexDigits.substr((s[19] & 0x3) | 0x8, 1);  // bits 6-7 of the clock_seq_hi_and_reserved to 01
        s[8] = s[13] = s[18] = s[23] = "-";

        var uuid = s.join("");
        return uuid;
    }
    , get: function (url, data, callback) {
        if ($.isFunction(data)) {
            callback = data;
            data = undefined;
        }

        url = parseUrl(url);
        var ret = execAjax("GET", url, data, callback);
        return ret;
    }
    , post: function (url, data, callback) {
        if ($.isFunction(data)) {
            callback = data;
            data = undefined;
        }

        var ret = execAjax("POST", url, data, callback);
        return ret;
    }
    , alert: function (msg, callBack, icon) {
        coreAlert(msg, callBack, icon);
    }
    , confirm: function (msg, callBack) {
        layerConfirm(msg, callBack);
    }
    , msg: function (msg, callBack, icon, time) {
        coreMsg(msg, callBack, icon, time);
    }
    , reload: function () {
        location.reload();
        return false;
    }
    , highlight: function ($el, keyword) {
        if (keyword) {
            var ym = $el.html();//.innerHTML;//ss是要高亮的区域，div的id值
            $el.html(ym.replace(keyword, "<span class='highlight_word'>" + keyword + "</span>"));
            //document.getElementById(id).innerHTML = ym.replace(keyword, "<span class='highlight_word'>" + keyword + "</span>");
        }
    }
    , getQueryParam: function (name) {
        if (name === null || name === undefined || name === "")
            return "";
        name = ("" + name).toLowerCase();
        var search = location.search.slice(1);
        var arr = search.split("&");
        for (var i = 0; i < arr.length; i++) {
            var ar = arr[i].split("=");
            if (ar[0].toLowerCase() === name) {
                if (unescape(ar[1]) === 'undefined') {
                    return "";
                } else {
                    return unescape(ar[1]);
                }
            }
        }
        return "";
    }
    , getQueryParams: function () {
        var params = {};
        var loc = window.location;
        var se = decodeURIComponent(loc.search);

        if (!se) {
            return params;
        }

        var paramsString;
        paramsString = se.substr(1);//将?去掉
        var arr = paramsString.split("&");
        for (var i = 0; i < arr.length; i++) {
            var item = arr[i];
            var index = item.indexOf("=");
            if (index === -1)
                continue;
            var paramName = item.substr(0, index);
            if (!paramName)
                continue;
            var value = item.substr(index + 1);
            params[paramName] = value;
        }
        return params;
    }
    , getOptionTextByValue: function (optionList, value, valuePropName, textPropName) {
        valuePropName = valuePropName || "Value";
        textPropName = textPropName || "Text";

        var text = "";
        var len = optionList.length;
        for (var i = 0; i < len; i++) {
            if (optionList[i][valuePropName] === value) {
                text = optionList[i][textPropName];
                break;
            }
        }

        return text;
    }
    , selectRow: function (selectedTr) {
        var c = "warning";
        $(selectedTr).addClass(c);
        $(selectedTr).siblings().removeClass(c);
        return true;
    }
    , formatBool: function (val) {
        if (val === true) {
            return "是";
        }
        else if (val === false) {
            return "否";
        }

        return val;
    }
    , download: function (url, method) {
        if (url) {

            $('<form action="' + url + '" method="' + (method || 'post') + '"></form>').appendTo('body').submit().remove();
        };
    }
    , upload: function (url, data) {
        if (url && data) {
            data = typeof data === 'string' ? data : jQuery.param(data);
            var inputs = '';
            $.each(data.split('&'), function () {
                var pair = this.split('=');
                inputs += '<input type="file" name="' + pair[0] + '" value="' + pair[1] + '" />';
            });
            $('<form enctype="multipart/form-data"    action="' + url + '" method="' + ('post') + '">' + inputs + '</form>').appendTo('body').submit().remove();
        };
    }
    , LoadVueComponents: function (components) {
        var deferred = $.Deferred();
        //加载Vue组件
        require(["/Content/vueTemplates/_loader.js"], function (loader) {
            loader.Load(components).then(function () {
                deferred.resolve();
            });
        });
        return deferred;
    }
    , clone: function (obj) {
        return JSON.parse(JSON.stringify(obj));
    }
};
function execAjax(type, url, data, callback) {
    //var layerIndex = layer.load(1, {
    //    shade: [0.3, '#000'] //0.3透明度的黑色背景
    //});
    var ret = $.ajax({
        url: url,
        type: type,
        dataType: "json",
        data: data,
        complete: function (xhr) {
            //layer.close(layerIndex);
            ;
        },
        success: function (result) { 
            var isStandardResult = ("code" in result) && ("msg" in result);
            if (isStandardResult) {
                //if (result.code === -1) {
                //    coreAlert(result.msg || "操作失败", null, 2);
                //    return;
                //}
                //if (result.Status === ResultStatus.NotLogin) {
                //    layerAlert(result.Msg || "未登录或登录过期，请重新登录");
                //    return;
                //}
                //if (result.Status === ResultStatus.Unauthorized) {
                //    layerAlert(result.Msg || "权限不足，禁止访问");
                //    return;
                //}

                //if (result.code === 0) {
                //    /* 传 result，用 result.Data 还是 result.Msg，由调用者决定 */
                //    callback(result);
                //}
                callback(result);
            }
            else
                callback(result);
        },
        error: errorCallback
    });
    return ret;
}
function errorCallback(xhr, textStatus, errorThrown) {
    var json = { textStatus: textStatus, errorThrown: errorThrown };
    alert("请求失败: " + JSON.stringify(json));
}
function parseUrl(url) {
    if (url.indexOf("_dc=") < 0) {
        if (url.indexOf("?") >= 0) {
            url = url + "&_dc=" + (new Date().getTime());
        } else {
            url = url + "?_dc=" + (new Date().getTime());
        }
    }
    return url;
};